package com.elite.km.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.elite.km.annotation.AdminApiRestController;
import com.elite.km.bean.Result;
import com.elite.km.bean.SessionStaff;
import com.elite.km.bean.UserContainer;
import com.elite.km.config.ArticleConfigInfos;
import com.elite.km.constant.Constants;
import com.elite.km.controller.BaseController;
import com.elite.km.dao.SyscParameterDAO;
import com.elite.km.dto.ArticleDTO;
import com.elite.km.dto.ArticlePathDTO;
import com.elite.km.dto.param.*;
import com.elite.km.entity.Article;
import com.elite.km.entity.TreeNode;
import com.elite.km.mapper.ArticleMapper;
import com.elite.km.mapper.TreeNodeMapper;
import com.elite.km.service.IArticleService;
import com.elite.km.service.ITreeNodeService;
import com.elite.km.service.SearchArticleService;
import com.elite.km.service.UtilityService;
import com.elite.km.thread.ArticleIndexesThread;
import com.elite.km.thread.ArticlesIndexesThread;
import com.elite.km.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sher
 */
@Slf4j
@Api(tags = "文章Admin", value = "ArticleController")
@AdminApiRestController
@RequestMapping(value = "/article", produces = {"application/json; charset=UTF-8"})
public class ArticleAdminController extends BaseController {
    private static final String PROMPT = "admin.controller.article.notExistAndPleaseRefresh";

    @Autowired
    private UtilityService kmUtilityService;
    @Autowired
    private ITreeNodeService treeNodeService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleConfigInfos articleConfigInfos;
    @Autowired(required = false)
    private SearchArticleService searchArticleService;
    @Autowired
    private TreeNodeMapper treeNodeMapper;

    @ApiOperation("新增")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result articleCreate(@RequestBody Article article) throws IllegalAccessException {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (StringUtil.isEmptyAfterTrim(article.getArticleTitle())) {
            return Result.failed(I18nUtils.get("admin.controller.privilegeTree.createNameIsEmpty", locale));
        }
        if (articleService.countTitleByParent(article) > 0) {
            // 判断重复标题文件是否是回收站的
            if (articleService.countTitleByTitleAndNodeParentIdAndStatus0(article) > 0) {
                return Result.failed(I18nUtils.get("admin.articleIsExistRecycle", locale));
            }
            return Result.failed(I18nUtils.get("admin.articleIsExist", locale));
        }
        String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String articleGuid = UIDUtil.getUUID();
        article.setArticleGuid(articleGuid);
        if (StringUtil.isEmpty(article.getArticleAId())) {
            article.setArticleAId(articleGuid);
        }
        String articleAId = UIDUtil.fetchArticleAId(article.getArticleAId(), epId);
        article.setArticleAId(articleAId);

        // 判断文章是否存在
        if (articleService.countById(articleAId) > 0) {
            return Result.failed("新建文章失败! 有重复的id存在，当前新建的文章id为[" + articleAId + "]");
        }
        // 新建文章时, 先给默认建一个html文件
        boolean creatFileFlag = ArticleUtil.submitKMByUsedTemplate(request, epId, articleAId, "", "");
        log.debug("从文章模板复制到知识库:  {}", creatFileFlag);
        String path = config.getSubmitMyKMNode() + "/" + articleAId + ".htm";
        // 上传文件到fs
        String ngsToken = (String) WebUtil.getSessionAttribute(request, Constants.SESSION_NGS_TOKEN);
        if (creatFileFlag && config.isUseLoadBalance()) {
            File file = new File(ArticleUtil.getArticleServerPath(path));
            JSONObject upd_Json = HttpUtil.ngsUploadFilePost(ngsToken, file, FileUtil.mergeSubmitMyKMNodePathUploadDir());
            log.debug("从文章模板上传到NGS:  {}", upd_Json);
        }
        article.setPath(path);
        // 默认过期时间
        int defaultValidateToDay = NumberUtil.parseInt(SyscParameterDAO.findSyscParameterWithDefaultValue("KMDVTD", epId, "30"));
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, defaultValidateToDay);
        article.setValidateTo(DateUtils.parseDateToTimestamp(cal.getTime()));
        article.setArticleAuthor(staff.getStaffName());
        article.setAuthorId(staff.getStaffId());
        article.setModifiedBy(staff.getStaffId());
        int insertCount = articleService.saveUtilityArticle(article);
        if (insertCount > 0) {
            return Result.success(article, I18nUtils.get("admin.createArticleSuccess", locale));
        }
        return Result.failed(I18nUtils.get("admin.createArticleFailed", locale));
    }

    @ApiOperation("删除文章到回收站/彻底删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result articleDelete(@RequestBody ArticleParam articleParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String articleAId = articleParam.getArticleAId();
        // 判断文章是否存在
        if (articleService.countById(articleAId) < 1) {
            return Result.failed(I18nUtils.get(PROMPT));
        }
        try {
            searchArticleService.deleteArticleIndexById(articleAId);
            log.debug("ES中文章id为[{}]删除成功:", articleAId);
            //更新缓存中的文章状态
            String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
            Map<String, ArticleDTO> articleDtoMap = cache.getAllArticles();
            ArticleDTO articleDTO = articleDtoMap.get(articleAId);
            if (articleDTO != null) {
                articleDTO.setStatus(0);
                articleDtoMap.put(articleAId, articleDTO);
                cache.setAllArticles(epId, articleDtoMap);
                log.debug("------- update cache status success ------");
            }
        } catch (Exception e) {
            log.error("", e);
        }
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        articleParam.setDeleteBy(staff.getStaffId());
        int count = articleService.removeArticle(articleParam);
        if (count == 1) {
            return Result.success(null, I18nUtils.get("admin.articleDeteleSuccess", locale));
        }
        return Result.failed(I18nUtils.get("admin.articleDeteleFailed", locale));
    }

    @ApiOperation("批量删除")
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result articleBatchDelete(@RequestBody List<String> articleAIds) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleAIds)) {
            return Result.failed(I18nUtils.get("admin.parameterEmpty", locale));
        }
        int count = articleService.removeByArticleAIds(articleAIds);
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed(I18nUtils.get("admin.deteleFailed", locale));
    }

    @ApiOperation("修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result articleUpdate(@RequestBody ArticleParam articleParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String articleAId = articleParam.getArticleAId();
        // 判断文章是否存在
        if (articleService.countById(articleAId) < 1) {
            return Result.failed(I18nUtils.get(PROMPT));
        }
        if (articleService.countTitleByArticle(articleParam) > 0) {
            return Result.failed(I18nUtils.get("admin.articleIsExistRecycle", locale));
        }
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        articleParam.setModifiedBy(staff.getStaffId());
        int count = articleService.updateArticleParam(articleParam);
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("直接上传文章文件")
    @RequestMapping(value = "/updateFile", method = RequestMethod.POST)
    public Result articleUpdateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam String articleAId) throws IllegalAccessException {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (multipartFile == null || multipartFile.isEmpty()) {
            return Result.failed(I18nUtils.get("controller.common.uploadFileEmpty"));
        }
        String fileExtension = FileUtil.getFileExtension(multipartFile.getOriginalFilename());
        if (!ArticleUtil.isArticleFile(fileExtension)) {
            return Result.failed(I18nUtils.get("admin.isNotArticleType", locale));
        }
        // 判断文章是否存在
        if (articleService.countById(articleAId) < 1) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        Article article = articleService.getOne(new LambdaQueryWrapper<Article>().eq(Article::getArticleAId, articleAId));
        String articlePath = ArticleUtil.getArticlePathWithSubmitMyKMNode(FileUtil.uploadFileToPath(multipartFile, ArticleUtil.getArticleStoreServerPath(config.getSubmitMyKMNode()), true, FileUtil.filterName(article.getArticleTitle())));
        log.debug("articlePath:{}", articlePath);
        // 同步到fs
        String ngsToken = (String) WebUtil.getSessionAttribute(request, Constants.SESSION_NGS_TOKEN);
        String path = ArticleUtil.getArticleServerPath(articlePath);
        log.debug("path:{}", path);
        if ("xlsx".equalsIgnoreCase(fileExtension) || "xls".equalsIgnoreCase(fileExtension)) {
            String newPath = path.replaceFirst("[.][^.]+$", ".html");
            articlePath = articlePath.replaceFirst("[.][^.]+$", ".html");
            //这里把excel转成html，然后用转后的文件去上传
            if (ExcelToHtmlUtil.toHtml(new File(path), newPath)) {
                path = newPath;
            }
        }
        if (config.isUseLoadBalance()) {
            File file = new File(path);
            JSONObject jsonObject = HttpUtil.ngsUploadFilePost(ngsToken, file, FileUtil.mergeSubmitMyKMNodePathUploadDir());
            log.debug("jsonObject: {}", jsonObject);
            if ("docx".equalsIgnoreCase(fileExtension) || "doc".equalsIgnoreCase(fileExtension)) {
                //这里涉及到word类型的回溯，将源文件先转为html再下载到指定位置
                String wordPath = jsonObject.getString("value");
                HttpUtil.wordChangeHtml(wordPath);
                HttpUtil.downLoadFileTemplate(wordPath.replaceFirst("[.][^.]+$", ".html"), path.replaceFirst("[.][^.]+$", ".html"));
                articlePath = articlePath.replaceFirst("[.][^.]+$", ".html");
            }
        }
        String finalPath = articlePath;
        log.debug("finalPath: {}", finalPath);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("pathWidthArticleStore", ArticleUtil.getPathWidthArticleStoreByPath(finalPath));
        resultMap.put("path", finalPath);
        return Result.success(resultMap);
    }

    @ApiOperation("修改父节点")
    @RequestMapping(value = "/updateParent", method = RequestMethod.POST)
    public Result articleUpdateParent(@RequestBody Article article) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        // 判断文章是否存在
        if (articleService.countById(article.getArticleAId()) < 1) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        int count = articleService.updateParent(article);
        if (count > 0) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("修改父节点")
    @RequestMapping(value = "/move2Parent", method = RequestMethod.POST)
    public Result articleMove2Parent(@RequestBody Article article) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        //审核通过的文章
        article.setAuditStatus(1);
        // 判断文章是否存在
        if (articleService.countById(article.getArticleAId()) < 1) {
            return Result.failed(I18nUtils.get(PROMPT));
        }
        if (treeNodeService.countById(article.getNodeParentAId()) < 1) {
            return Result.failed(I18nUtils.get("admin.controller.articleNode.notExistAndPleaseRefresh", locale));
        }
        if (articleService.countTitleByArticle(article) > 0) {
            return Result.failed(I18nUtils.get("admin.node.articleNameIsExist", locale));
        }
        int count = articleService.updateParent2(article);
        if (count > 0) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("文章详情")
    @RequestMapping(value = "/detail", method = {RequestMethod.GET})
    public Result articleDetail(@RequestParam String articleAId) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        // 判断文章是否存在
        if (articleService.countById(articleAId) < 1) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
        log.debug("epId: [{}], articleAId: [{}]", epId, articleAId);
        ArticleDTO articleDto = articleService.getArticleDetail(epId, articleAId);
        if (articleDto != null) {
            // 处理gbk编码的txt
            if (StringUtil.isNotNull(articleDto.getPath())) {
                articleDto.setPathWidthArticleStore(ArticleUtil.getPathWidthArticleStoreByPath(articleDto.getPath()));
            }
            if (!config.isReview() || StringUtil.isNull(articleDto.getApprovePath())) {
                articleDto.setApprovePath(articleDto.getPath());
            }
            //可能存在修改文章节点名称的操作，这时候需要刷新缓存
            List<ArticlePathDTO> articlePathDTO = articleService.queryArticlePath(articleAId);
            String authorityTitle = "";
            String folder = "";
            if (articlePathDTO != null && articlePathDTO.size() > 0 && articlePathDTO.get(0) != null) {
                authorityTitle = articlePathDTO.get(0).getAuthorityTitle();
                folder = articlePathDTO.get(0).getFolder();
            }
            log.debug("authorityTitle:[{}],folder:[{}]", authorityTitle, folder);
            String wholePath = authorityTitle + "-" + folder;
            if (StringUtils.isEmpty(authorityTitle) || StringUtils.isEmpty(folder)) {
                wholePath = cache.getTreeNodeFullNamePathAll(articleDto.getNodeParentAId(), "-", epId);
            }
            log.debug("wholePath: {}", wholePath);
            articleDto.setWholePath(wholePath);
            TreeNode treeNode = treeNodeMapper.queryParentId(articleDto.getNodeParentAId());
            articleDto.setNodeParentAIdTitle(treeNode == null ? "" : treeNode.getNodeTitle());
            return Result.success(articleDto);
        }
        return Result.failed(I18nUtils.get("admin.requestFailed", locale));
    }

    @ApiOperation("查询同父节点下文章标rbList题是否重复")
    @RequestMapping(value = "/checkTitle", method = RequestMethod.POST)
    public Result checkArticleTitle(@RequestBody ArticleParam articleParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String articleAId = articleParam.getArticleAId();
        // 判断文章是否存在
        if (articleService.countById(articleAId) < 1) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        // 判断当前标题的文章是否存在
        if (articleService.countTitleByArticle(articleParam) >= 1) {
            return Result.failed(I18nUtils.get("admin.articleNameIsExist", locale));
        }
        return Result.success(null);
    }

    @ApiOperation("删除文章到回收站")
    @RequestMapping(value = "/rbList", method = RequestMethod.GET)
    public Result rbArticleList() {
        List<ArticleDTO> rbArticleList = articleService.listRbArticle();
        return Result.success(rbArticleList);
    }

    @ApiOperation("回收站文章删除")
    @RequestMapping(value = "/rbDelete", method = RequestMethod.POST)
    public Result rbArticleDelete(@RequestBody List<String> articleAIds) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleAIds)) {
            return Result.failed(I18nUtils.get("admin.deteleArticleFailed", locale));
        }
        UserContainer userContainer = (UserContainer) session.getAttribute(Constants.USER_CONTAINER);
        String staffId = userContainer.getStaff().getId();
        int count = articleService.deleteArticleByIds(articleAIds, staffId);
        return Result.success(count);
    }

    @ApiOperation("回收站文章恢复")
    @RequestMapping(value = "/rbRecovery", method = RequestMethod.POST)
    public Result rbArticleRecovery(@RequestBody RbRecoveryParam rbRecoveryParam) {
        List<Map<String, String>> articleAIds = rbRecoveryParam.getArticleDetails();
        boolean recoveryAgain = rbRecoveryParam.isRecoveryAgain();
        boolean isList = rbRecoveryParam.isBatch();
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleAIds)) {
            return Result.failed(I18nUtils.get("admin.rbRecoveryArticleFailed", locale));
        }
        UserContainer userContainer = (UserContainer) session.getAttribute(Constants.USER_CONTAINER);
        String staffId = userContainer.getStaff().getId();
        int count = 0;
        if (recoveryAgain) {
            count = articleService.recoveryAndCoverArticle(articleAIds.get(0), staffId);
        } else {
            count = articleService.recoveryArticleByIds(articleAIds, staffId, isList);
        }
        if (count == articleAIds.size()) {
            return Result.success(null, I18nUtils.get("admin.rbRecoverySuccess", locale));
        } else if (count == -1) {
            return Result.failed(I18nUtils.get("admin.rbRecoveryIllegality", locale));
        } else if (count == -2) {
            return Result.failed(-240515, I18nUtils.get("admin.rbRecoveryFailed", locale));
        } else if (count == -3) {
            return Result.failed(I18nUtils.get("admin.rbRecoveryBatchFailed", locale));
        } else if (count == -4) {
            return Result.failed(I18nUtils.get("admin.rbRecoveryBatchRepeat", locale));
        } else {
            return Result.success(null, I18nUtils.get("admin.rbRecoveryPartSuccess", locale));
        }
    }

    @ApiOperation("批量上传时覆盖")
    @RequestMapping(value = "/batchCover", method = RequestMethod.POST)
    public Result articleBatchCover(@RequestBody List<String> articleBatchGuids) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleBatchGuids)) {
            return Result.failed(I18nUtils.get("admin.batchCoverIsEmpty", locale));
        }
        boolean isUpdate = articleService.updateArticleByBatchCover(request, articleBatchGuids);
        if (isUpdate) {
            return Result.success(null);
        } else {
            return Result.failed(I18nUtils.get("admin.batchCoverFailed", locale));
        }
    }

    @ApiOperation("文章节点维护， 文章头像上传")
    @RequestMapping(value = "/headImageUpload", method = RequestMethod.POST)
    public Result articleHeadImgUpload(@RequestParam MultipartFile file) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (file == null || file.isEmpty()) {
            return Result.failed(I18nUtils.get("admin.controller.treeNode.uploadFileEmpty", locale));
        }
        String fileName = FileUtil.uploadFileToPath(file, ArticleUtil.getArticleHeadImgServerPath(), false);
        if (!"".equalsIgnoreCase(fileName)) {
            return Result.success(articleConfigInfos.getArticleHeadImagePath() + '/' + fileName, "文章头像上传成功!");
        }
        return Result.failed(I18nUtils.get("admin.avatarUploadFailed", locale));
    }

    @ApiOperation("文章维护，如果文章没有path，则新建文章path并且生成文件")
    @RequestMapping(value = "/newFile", method = RequestMethod.POST)
    public Result articleNewFile(@RequestParam String epId, @RequestParam String articleAId) throws Exception {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        String path = config.getSubmitMyKMNode() + '/' + articleAId + ".htm";
        log.debug("articleAId: [{}]", articleAId);
        ArticleDTO article = ArticleDTO.builder().build();
        article.setArticleAId(articleAId);
        article.setPath(path);

        int updateRow = articleService.updateArticlePath(epId, article);
        if (updateRow > 0) {
            ArticleUtil.createArticleFile(request, epId, ArticleUtil.getArticleStoreServerPath() + "/" + path);
            ArticleDTO articleDto = ArticleDTO.builder().build();
            articleDto.setPath(path);
            articleDto.setPathWidthArticleStore(ArticleUtil.getPathWidthArticleStoreByPath(path));
            return Result.success(articleDto);
        }
        return Result.failed(I18nUtils.get("admin.articleContentCreateFailed", locale));
    }


    @ApiOperation("文章审核 - 删除到")
    @RequestMapping(value = "/auditDelete", method = RequestMethod.POST)
    public Result articleAuditDelete(@RequestBody ArticleAuditParam articleAuditParam) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (articleService.countById(articleAuditParam.getArticleAId()) == 0) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        articleAuditParam.setOperator(staff.getStaffId());
        int count = kmUtilityService.deleteAuditArticle(articleAuditParam);
        return Result.success(null);
    }

    @ApiOperation("文章审核 - 更新基本文章")
    @RequestMapping(value = "/auditUpdate", method = RequestMethod.POST)
    public Result articleAuditUpdate(@RequestBody ArticleAuditParam articleAuditParam) throws Exception {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        articleAuditParam.setModifiedBy(staff.getStaffId());
        if (StringUtil.isEmpty(StringUtil.trimToEmpty(articleAuditParam.getArticleTitle()))) {
            return Result.failed(I18nUtils.get("admin.articleTitleIsNotEmpty", locale));
        }
        // 判断当前标题的文章是否存在
        if (articleService.countById(articleAuditParam.getArticleAId()) <= 0) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        int count = articleService.updateAuditArticle(request, articleAuditParam);
        if (count >= 1) {
            return Result.success(count);
        }
        return Result.failed();
    }

    @ApiOperation("文章审核 - 审核通过")
    @RequestMapping(value = "/auditPass", method = RequestMethod.POST)
    public Result articleAuditPass(@RequestBody ArticleAuditParam articleAuditParam) {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        articleAuditParam.setAuditBy(staff.getStaffId());
        int count = kmUtilityService.passAuditArticle(articleAuditParam);
        log.debug("passAuditArticle count:{}", count);
        if (count > 0) {
            //审核通过开始刷新索引
            ArticleDTO articleDto = articleMapper.getArticleDTO(articleAuditParam.getArticleAId());
            ExecutorService executor = Executors.newSingleThreadExecutor();
            if (config.isUseLoadBalance()) {
                executor.execute(new ArticlesIndexesThread("", UIDUtil.getUUID(), (String) WebUtil.getSessionAttribute(request, Constants.SESSION_NGS_TOKEN), Arrays.asList(articleDto), null, false));
            } else {
                executor.execute(new ArticleIndexesThread((String) WebUtil.getSessionAttribute(request, Constants.EPID), articleDto));
            }
            return Result.success(null);
        }
        return Result.failed(I18nUtils.get("api.create.article", locale));
    }

    @ApiOperation("文章审核 - 审核驳回")
    @RequestMapping(value = "/auditReject", method = RequestMethod.POST)
    public Result articleAuditReject(@RequestBody ArticleAuditParam articleAuditParam) {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        articleAuditParam.setOperator(staff.getStaffId());
        int count = kmUtilityService.rejectAuditArticle(articleAuditParam);
        return Result.success(null);
    }

    @ApiOperation("文章审核 - 从回收站恢复")
    @RequestMapping(value = "/auditRecovery", method = RequestMethod.POST)
    public Result articleAuditRecovery(@RequestParam String articleAId) {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String staffId = staff.getStaffId();
        int count = kmUtilityService.recoveryAuditArticle(articleAId, staffId);
        return Result.success(null);
    }


    @ApiOperation("过期文章 - 删除")
    @RequestMapping(value = "/offlineDelete", method = RequestMethod.POST)
    public Result offlineArticleDelete(@RequestBody List<String> articleAIds) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleAIds)) {
            return Result.failed(I18nUtils.get("admin.parameterEmpty", locale));
        }
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        int count = articleService.removeToRbByArticleAIds(articleAIds, staff.getStaffId());
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed(I18nUtils.get("admin.deteleFailed", locale));
    }

    @ApiOperation("下架文章 - 批量修改下架时间")
    @RequestMapping(value = "/updateOfflineDate", method = RequestMethod.POST)
    public Result offlineArticleUpdateOfflineDate(@RequestBody OfflineArticleParam offlineArticleParam) {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String staffId = staff.getStaffId();
        int count = articleService.updateBatchOfflineDate(offlineArticleParam, staffId);
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("下架文章列表")
    @RequestMapping(value = "/offlineList", method = RequestMethod.GET)
    public Result offlineArticleList() {
        return Result.success(articleService.queryAllOfflineArticles());
    }

    @ApiOperation("过期文章 - 删除")
    @RequestMapping(value = "/expiredDelete", method = RequestMethod.POST)
    public Result expiredArticleDelete(@RequestBody List<String> articleAIds) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (CollectionsUtils.isEmpty(articleAIds)) {
            return Result.failed(I18nUtils.get("admin.parameterEmpty", locale));
        }
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        int count = articleService.removeToRbByArticleAIds(articleAIds, staff.getStaffId());
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed(I18nUtils.get("admin.deteleFailed", locale));
    }

    @ApiOperation("过期文章 - 修改")
    @RequestMapping(value = "/expiredUpdate", method = RequestMethod.POST)
    public Result expiredArticleUpdate(@RequestBody Article article) {
        Locale locale = config.getUserLocale((String) session.getAttribute("locale"));
        if (StringUtil.isEmpty(StringUtil.trimToEmpty(article.getArticleTitle()))) {
            return Result.failed(I18nUtils.get("admin.articleTitleIsNotEmpty", locale));
        }
        if (articleService.countById(article.getArticleAId()) <= 0) {
            return Result.failed(I18nUtils.get(PROMPT, locale));
        }
        boolean isUpdate = articleService.update(article, new LambdaUpdateWrapper<Article>().eq(Article::getArticleAId, article.getArticleAId()));
        if (isUpdate) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("过期文章 - 批量修改过期时间")
    @RequestMapping(value = "/updateExpiredDate", method = RequestMethod.POST)
    public Result expiredArticleUpdateExpiredDate(@RequestBody ExpiredArticleParam expiredArticleParam) throws Exception {
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        String staffId = staff.getStaffId();
        int count = kmUtilityService.updateBatchExpiredDate(expiredArticleParam, staffId);
        if (count >= 0) {
            return Result.success(null);
        }
        return Result.failed();
    }

    @ApiOperation("过期文章 - 列表")
    @RequestMapping(value = "/expiredList", method = RequestMethod.GET)
    public Result loadExpiredArticles() {
        String epId = (String) WebUtil.getSessionAttribute(request, Constants.EPID);
        SessionStaff staff = (SessionStaff) WebUtil.getSessionAttribute(request, Constants.SESSION_STAFF);
        List<ArticleDTO> resultExpiredArticles = articleService.queryAllExpireArticles();
        //		// 过期文章根据登录人过滤
        //		if (!staff.isSuperman()) {
        //			List<String> topKMTreeNodeAIds = treeNodeService.getTopKMTreeNodeAIdsByRolegroupId(epId, staff.getStaffRoleGroupId().get(0));
        //			List<TreeNodeDto> allSubKMTreeNodes = treeNodeService.getAllNotTopTreeNodes(epId);
        //			log.info("expiredArticles.size(): {}", resultExpiredArticles.size());
        //			resultExpiredArticles = articleService.getExpiredArticlesInRoleGroupForIndex(topKMTreeNodeAIds, allSubKMTreeNodes, resultExpiredArticles);
        //			resultExpiredArticles.sort((articleDto1, articleDto2) -> {
        //				String articleAId1 = articleDto1.getArticleAId();
        //				String articleAId2 = articleDto2.getArticleAId();
        //				Timestamp validateTo1 = articleDto1.getValidateTo();
        //				Timestamp validateTo2 = articleDto2.getValidateTo();
        //
        //				if (validateTo1 == null && validateTo2 == null) {
        //					return articleAId1.compareTo(articleAId2);
        //				}
        //				if (validateTo1 == null) {
        //					return -1;
        //				}
        //				if (validateTo2 == null) {
        //					return 1;
        //				}
        //				if (validateTo1.getTime() - validateTo2.getTime() > 0) {
        //					return 1;
        //				} else if (validateTo1.getTime() - validateTo2.getTime() == 0) {
        //					return articleAId1.compareTo(articleAId2);
        //				} else {
        //					return -1;
        //				}
        //			});
        //		}
        return Result.success(resultExpiredArticles);
    }

}
